package thesis.filesharing.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import thesis.filesharing.common.exception.system.AppSystemException;
import thesis.filesharing.dao.RoleDAO;
import thesis.filesharing.dao.util.EMF;
import thesis.filesharing.model.Role;

import com.google.appengine.api.datastore.Key;

@Repository
public class RoleDAOImpl implements RoleDAO {

	@Override
	public Role getRoleByKey(Key key) {
		EntityManager em = null;
		try {
			em = EMF.get().createEntityManager();
			Role role = em.find(Role.class, key);
			return role;
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new AppSystemException(ex);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public Role getRoleByName(String roleName) {
		EntityManager em = null;
		try {
			em = EMF.get().createEntityManager();
			String jpaql = "SELECT r FROM Role r WHERE r.roleName = :roleName";
			Query query = em.createQuery(jpaql);
			query.setParameter("roleName", roleName);
			List<Role> roles = (List<Role>) query.getResultList();
			if (roles != null && !roles.isEmpty()) {
				return roles.get(0);
			}
			return null;
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new AppSystemException(ex);
		}
	}
}
